package virtualstock.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.InvalidParameterException;
import virtualstock.request.StockController;
import virtualstock.util.StockDetails;

/**
 * Servlet implementation class CreateStockServlet
 */
public class CreateStockServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private StockController stockController;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateStockServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
    	String name = (String) request.getParameter("name");
    	BigDecimal currentPrice = new BigDecimal((String) request.getParameter("currentprice"));
    	
    	try {
    		StockDetails details = new StockDetails(name, currentPrice);
    		Long stockID = stockController.createStock(details);
        	details.setStockID(stockID);
		} catch (InvalidParameterException e) {
			out.print("InvalidParameterException");
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("ListStockServlet").forward(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
